package com.shangye.core;

import com.shangye.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;

    private static File rootDir;
    private static File staticDir;
    static {

        try {
            rootDir = new File(ClientHandler.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }



    public ClientHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            HttpServletRequest request = new HttpServletRequest(socket);

            String path = request.getUri();
            File file = new File(staticDir, path);
            if (file.exists()){

                println("Http/1.1 200 OK");
                println("Cotent-Type: text/html");
                println("Contrnt-Length: " + file.length());
                println("");

                OutputStream out = socket.getOutputStream();
                FileInputStream fis = new FileInputStream(file);
                byte[] data = new byte[1024*10];
                int len;
                while ((len = fis.read(data))!= -1){
                    out.write(data,0,len);
                }

            }


        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void println(String line) throws IOException{
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);

    }


}
